﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Drawing;

using breakoutsharp.core;
using breakoutsharp.visual;
using breakoutsharp.visual.gameobject;

namespace breakoutsharp.utility
{
	public static class LevelLoader
	{
		public static Level LoadLevelFromFile(string s)
		{
			List<IBlock> blocks = new List<IBlock>();
			List<Ball> balls = new List<Ball>();
			StreamReader reader = new StreamReader(@"data\levels\" + s + ".lvl");
			string line;
			string[] coords;

			Block b;

			while (reader.EndOfStream == false)
			{
				line = reader.ReadLine();
				coords = line.Split(',');

				switch (coords[0])
				{
				case "Block":
					try
					{
						b = new Block((Block.BlockType)Enum.Parse(typeof(Block.BlockType), coords[3]));

					}
					catch
					{
						Logger.LogError("'" + coords[3] + "' could not be parsed as a block type in map file " + s);
						b = new Block(Block.BlockType.Normal);
					}

					b.Location = new Point(int.Parse(coords[1]), int.Parse(coords[2]));
					blocks.Add(b);
					break;
				case "Ball":
					PointF loc = new PointF(float.Parse(coords[1]), float.Parse(coords[2]));
					PointF direction = new PointF(float.Parse(coords[3]), float.Parse(coords[4]));
					int speed = int.Parse(coords[5]);
					balls.Add(new Ball(loc, direction)
					{
						Speed = speed
					});
					break;
				}
			}


			/* Clean up */
			reader.Dispose();

			return new Level(blocks, balls);
		}

		public static void SaveLevelToFile(FileInfo file, List<Block> block)
		{
			SaveLevelToFile(file, block, new List<Ball>());
		}

		public static void SaveLevelToFile(FileInfo file, List<Block> blocks, List<Ball> balls)
		{
			if ((blocks == null) | (balls == null))
			{
				throw new NullReferenceException();
			}


			StreamWriter writer = new StreamWriter(file.FullName);

			foreach (Block b in blocks)
			{
				writer.WriteLine("Block,{0},{1},{2}", b.Location.X, b.Location.Y, b.Type);
			}

			foreach (Ball b in balls)
			{
				writer.WriteLine("Ball,{0},{1},{2},{3}", b.Location.X, b.Location.Y, b.Direction.X, b.Direction.Y);
			}

			writer.Dispose();
		}

	}
}
